<?php

class UserController extends Controller
{
	public function actionIndex()
	{
		$this->redirect(array('manage', 'user_type' => 'C'));
	} 
	/*
	 * CTV
	 */
	public function actionManageCTV() {
		$this->activeMenu = 'ctv';

		$criteria=new CDbCriteria(array(
			'condition' => "user_type=:user_type",
			'order' => 'timestamp DESC',
			'params' => array(
				':user_type' => 'F',
			),
		));

		$dataProvider = User::model()->Search($criteria);

		$this->render('manage_ctv', array(
			'dataProvider' => $dataProvider,
		));
	}

	public function actionAddCTV() {
		$this->activeMenu = 'ctv';

		$model = new User;

		if ( app()->request->isPostRequest ) {
			if( isset($_POST['User']) ) {
				$model->attributes = $_POST['User'];
				$model->user_login = $model->email;

				// check exists
				$check = User::model()->findByAttributes(array(
					'user_login' => $model->user_login,
				));

				if ( !empty($check) ) {
//					$check->user_type = 'F';
//					$check->save(false);
//					$this->redirect(array('updateCTV', 'id' => $check->primaryKey));

					$model->addError('email', t('Email này đã tồn tại'));

				} elseif ( $model->validate() ) {
					if ( trim($model->password1) != '' )	{
						$model->password = $model->hashPassword($model->password1);
					}
					$model->setIsNewRecord(true);
					if( $model->createUser() ) {
						$this->redirect(array('updateCTV', 'id' => $model->primaryKey));
					}
				}
			}
		}

		$model->status = 'A';
		$model->user_type = 'F';
		$model->usergroup_ids = array();

		$this->render('update_ctv', array(
			'model' => $model,
		));
	}

	public function actionUpdateCTV() {
		$this->activeMenu = 'ctv';

		$id = getQuery('id');

		if ( $id ) {
			$model = User::model()->getUser($id);

			if ( app()->request->isPostRequest ) {
				if( isset($_POST['User']) ) {
					$model->attributes = $_POST['User'];

					$model->user_login = $model->email;
					if ( $model->validate() ) {
						if ( trim($model->password1) != '' )	{
							$model->password = $model->hashPassword($model->password1);
						}

						if( $model->save(false) )
							// save ctv products
							if ( $model->user_type == 'F' ) {
								$ctvProducts = getPost('CTVBooks');
								if ( !empty($ctvProducts) ) {
									$model->saveCtvProducts($ctvProducts);
								}
							}

							$this->redirect(array('updateCTV', 'id' => $model->user_id));
					}
				}
			}

			$this->render('update_ctv', array(
				'model' => $model,
			));
		} else {
			//$this->redirect(array('manage', 'user_type' => 'C'));
		}
	}

	/*
	 * USERS
	 */
	public function actionManage()
	{
		$user_type = getQuery('user_type', 'C');
		$filters = getQuery('filter', array());

		$criteria=new CDbCriteria(array(
			'condition' => "user_type=:user_type",
			'order' => 'timestamp DESC',
			'params' => array(
				':user_type' => $user_type
			),
		));
		
		if ( !empty($filters) ) {
			User::applyFilters($criteria, $filters);
		}

		$dataProvider = User::model()->Search($criteria);

		$this->render('manage', array(
			'dataProvider'=>$dataProvider,
			'filter' => $filters,
		));
	}

	public function actionAdd() {
		$model = new User;

		if ( app()->request->isPostRequest ) {
			if( isset($_POST['User']) ) {
				$model->attributes = $_POST['User'];

				$model->user_login = $model->email;
				if ( $model->validate() ) {
					if ( trim($model->password1) != '' )	{
						$model->password = $model->hashPassword($model->password1);
					}
					$model->setIsNewRecord(true);

					if( $model->save(false) ) {
						// save usergroups
						$usergroups = getPost('user_usergroups');
						if ( !empty($usergroups) ) {
							$model->setUsergroups($usergroups);
						}
						logInfo("New user with username '$model->user_login' has been added.");
						$this->redirect(array('update', 'id' => $model->user_id)); 
					}
				}
			}
		}

		$model->status = 'A';
		$model->user_type = $_GET['user_type'];
		$model->usergroup_ids = array();

		$usergroupsDataProvider = new CActiveDataProvider('Usergroup', array(
			'criteria' => array(
				'condition' => "status='A'",
			),
		));

		$this->render('update', array(
			'model' => $model,
			'usergroupsDataProvider' => $usergroupsDataProvider,
		));
	}

	public function actionUpdate()
	{
		$id = getQuery('id');

		if ( $id ) {
			$model = User::model()->getUser($id);
			if ( $model->user_type == 'F' ) {
				$this->redirect(array('/user/updateCTV', 'id' => $id));
			}

			if ( app()->request->isPostRequest ) {
				if( isset($_POST['User']) ) {
					$model->attributes = $_POST['User'];

					$model->user_login = $model->email;
					if ( $model->validate() ) {
						if ( trim($model->password1) != '' )	{
							$model->password = $model->hashPassword($model->password1);
						}

						if( $model->save(false) )
							// save usergroups
							if ( $model->user_type == 'A' ) {
								$usergroups = getPost('user_usergroups');
								if ( !empty($usergroups) ) {
									$model->setUsergroups($usergroups);
								}
							}

							// save cp products
							if ( $model->user_type == 'B' ) {
								$cpProducts = getPost('cpProducts');
								if ( !empty($cpProducts) ) {
									$model->saveCpProducts($cpProducts);
								}
							}
							logInfo("User with user name '$model->user_login' has been updated");
							$this->redirect(array('update', 'id' => $model->user_id));
					}
				}
			}

			$usergroupsDataProvider = new CActiveDataProvider('Usergroup', array(
				'criteria' => array(
					'condition' => "status='A'",
				),
			));

			$this->render('update', array(
				'model' => $model,
				'usergroupsDataProvider' => $usergroupsDataProvider,
			));
		} else {
			//$this->redirect(array('manage', 'user_type' => 'C'));
		}
	}

	public function actionDelete()
	{
		$id = getQuery('id');

		if ( $id ) {
			$user = User::model()->findByPk($id);
			if ( User::model()->deleteByPk($id) ) {
				// delete usegroup of users
				$delete_command = app()->db->createCommand("DELETE FROM {{usergroup_links}} WHERE user_id=:user_id");
				$delete_command->execute(array(':user_id' => $id));
				if($user) logInfo("User with user name '$user->user_login' has been updated");
				// set notifications
				if ( isAjaxRequest() || isset($_GET['ajax']) ) {
					echo 'Deleted Successfully.';
					app()->end();
				} else {
					//user()->setNotification('N', t('notice'), t('Delete Successfully.'));
					$this->redirect(array('manage'));
				}
			}
		}

		$this->redirect(array('manage'));
	}

	public function actionUpdateStatus() {
		$status = getQuery('status');
		$id = getQuery('id');
		$table = getQuery('table'); // not used
		$id_name = getQuery('id_name'); // not used
		$user = User::model()->findByPk($id);
		
		$command = app()->db->createCommand("UPDATE {{users}} SET status=:status WHERE user_id=:id LIMIT 1");
		if ( $command->execute(array(':status' => $status, ':id' => $id)) ) { 
			if($user) logInfo("User with user name '$user->user_login' has been updated");
			if (isAjaxRequest()) {
				user()->setNotification('N', t('notice'), t('Update status successfully.'));
				$this->renderAjax('//ajax/index');
			}
		}
		app()->end();
	}

	public function actionGetUser() {
		$user_type = 'B';
		$term = getParam('term');

		$term = addcslashes($term, '%_');
		$command = app()->db->createCommand("SELECT user_id AS id, name AS value, name AS label FROM {{users}} WHERE user_type=:user_type AND status=:status AND (LOWER(name) LIKE :name OR LOWER(user_login) LIKE :name)");
		$results = $command->queryAll(true, array(
			':user_type' => $user_type,
			':status' => 'A',
			':name' => "%".strtolower($term)."%",
			));

		echo CJSON::encode($results);
		app()->end();
	}

	/* User groups */
	function actionManageGroup() {
		$criteria=new CDbCriteria(array(
			//'condition' => "status='A'",
			'order' => 'usergroup ASC',
		));

		$dataProvider = Usergroup::model()->Search($criteria);

		$this->render('manage_group', array(
			'dataProvider' => $dataProvider,
		));
	}

	public function actionAddGroup() {
		$model = new Usergroup;

		if ( app()->request->isPostRequest ) {
			if( isset($_POST['Usergroup']) ) {
				$model->attributes = $_POST['Usergroup'];

				$model->setIsNewRecord(true);
				if( $model->save() )
					$privileges = getPost('set_privileges');
					$model->savePrivileges($privileges);
					logInfo("New user group with name '$model->usergroup' has been added.");
					$this->redirect(array('updateGroup', 'id' => $model->usergroup_id));
			}
		}

		$model->status = 'A';
		$model->group_privileges = array();

		$privileges = Privilege::model()->findAllPrivileges();

		$this->render('update_group', array(
			'model' => $model,
			'privileges' => $privileges,
		));
	}

	public function actionUpdateGroup()
	{
		$id = getQuery('id');

		if ( $id ) {
			$model = Usergroup::model()->getUsergroup($id);

			if ( app()->request->isPostRequest ) {
				if( isset($_POST['Usergroup']) ) {
					$model->attributes = $_POST['Usergroup'];

					if( $model->save() ) {
						$privileges = getPost('set_privileges');
						$model->savePrivileges($privileges);
						logInfo("User group with name '$model->usergroup' has been updated.");
						$this->redirect(array('updateGroup', 'id' => $model->usergroup_id));
					}
				}
			}

			$privileges = Privilege::model()->findAllPrivileges();

			$this->render('update_group', array(
				'model' => $model,
				'privileges' => $privileges,
			));
		} else {
			$this->redirect(array('manage', 'user_type' => 'C'));
		}
	}

	public function actionDeleteGroup()
	{
		$id = getQuery('id');

		if ( $id ) {
			$group = Usergroup::model()->findByPk($id);
			if ( Usergroup::model()->deleteByPk($id) ) {
				// delete usegroup of users
				$delete_command = app()->db->createCommand("DELETE FROM {{usergroup_links}} WHERE usergroup_id=:usergroup_id");
				$delete_command->execute(array(':usergroup_id' => $id));

				// delete usergroup privileges
				$delete_command = app()->db->createCommand("DELETE FROM {{usergroup_privileges}} WHERE usergroup_id=:usergroup_id");
				$delete_command->execute(array(':usergroup_id' => $id));
				
				if($group) logInfo("User group with name '$group->usergroup' has been deleted.");
				// set notifications
				if ( isAjaxRequest() || isset($_GET['ajax']) ) {
					echo 'Deleted Successfully.';
					app()->end();
				} else {
					user()->setFlash('delete_success', 'Delete Successfully.');
					$this->redirect(array('manage'));
				}
			}
		}

		$this->redirect(array('manage'));
	}

	public function actionUpdateGroupStatus() {
		$status = getQuery('status');
		$id = getQuery('id');
		$table = getQuery('table'); // not used
		$id_name = getQuery('id_name'); // not used
		$group = Usergroup::model()->findByPk($id);
		$command = app()->db->createCommand("UPDATE {{usergroups}} SET status=:status WHERE usergroup_id=:id LIMIT 1");
		if ( $command->execute(array(':status' => $status, ':id' => $id)) ) {
			if($group) logInfo("User group with name '$group->usergroup' has been updated.");
			if (isAjaxRequest()) {
				$this->renderAjax('//ajax/index');
			}
		}
		app()->end();
	}
}